/**
 * 
 */

package tests.laurens.gui_ti07;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLayeredPane;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.KeyStroke;
import javax.swing.SpringLayout;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.WindowConstants;
import javax.swing.text.html.HTMLDocument;


// import org.json.simple.*;

/**
 * @author Laurens
 * 
 */
public class GUI_Backup_TI07 {

	public static void main(String[] args) {
		setGUILookAndFeel();
		setContentPane();
		addBackground();
		addMenu();
		dudesClientWindows.addWindows();
		dudesClientWindows.fillWindows();

		SwingUtilities.invokeLater(new Runnable() {

			public void run() {
				SwingUtilities.updateComponentTreeUI(content);
			}
		});
	}

	// Variables
	// private static final String guiBackground = "background.jpg";
	// private static final String guiBackground = "hell.png";
	private static final String guiBackground = "worldmap-1920px.jpg";
	// Source: http://www.psdgraphics.com/backgrounds/world-map-background/

	// System path separator
	private static final String sep = (System.getProperty("file.separator") == "/") ? "/" : "\\";
	// Get image from images-directory
	public static final Image getDudesImage(String file) {
		Image image = null;
		try {
			image = Toolkit.getDefaultToolkit().getImage(
					Painter.class.getResource("images" + sep + file));
		} catch(Exception e) {}
		return image;
	}
	public static final Image getDudesIcon(String file) {
		Image image = null;
		try {
			image = Toolkit.getDefaultToolkit().getImage(
					Painter.class.getResource("images" + sep + "icons" + sep + file));
		} catch(Exception e) {}
		return image;
	}

	private static void setGUILookAndFeel() {
		UIManager.put("DesktopPane[Enabled].backgroundPainter", new Painter());
		try {
			for(LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
				if("Nimbus".equals(info.getName())) {
					UIManager.setLookAndFeel(info.getClassName());
					break;
				}
			}
		} catch(Exception e) {}
	}

	private static final JFrame content = new JFrame();
	public static final int windowSizeWidth = Toolkit.getDefaultToolkit().getScreenSize().width;
	public static final int windowSizeHeight = Toolkit.getDefaultToolkit().getScreenSize().height;
	private static void setContentPane() {
		content.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		content.setTitle("D.U.D.E.S. CMS - (c) 2011 Hogeschool INHolland, projectgroep 2");
		// Set application icon
		content.setIconImage(getDudesIcon("bomb.png"));
		content.setResizable(false); // Disable window to be resized
		content.pack(); // Prepare all elements to be shown
		content.setVisible(true); // Show screen
		/* content.setSize(windowSizeWidth, windowSizeHeight - 40); // Set
		 * window size: 1250x750 // Center position on screen Dimension
		 * screenSize = Toolkit.getDefaultToolkit().getScreenSize(); int
		 * locationX = (screenSize.width/2 - content.getWidth()/2); int
		 * locationY = (screenSize.height/2 - content.getHeight()/2);
		 * content.setLocation(locationX, locationY); */

		content.setMinimumSize(new Dimension(windowSizeWidth, windowSizeHeight));
		content.setExtendedState(content.getExtendedState() | JFrame.MAXIMIZED_BOTH);
	}
	private static JDesktopPane desktop = new JDesktopPane();
	private static void addBackground() {
		desktop.setBackground(new Color(196, 199, 206));
		desktop.setEnabled(false);

		desktop.setDragMode(JDesktopPane.LIVE_DRAG_MODE);
		content.add(desktop, BorderLayout.CENTER);
		desktop.setVisible(true);
	}

	private static void addMenu() {
		content.setJMenuBar(createMenuBar());
	}
	protected static JMenuBar createMenuBar() {
		JMenuBar menuBar = new JMenuBar();

		// File menu
		JMenu menuFile = new JMenu("File");
		menuFile.setMnemonic(KeyEvent.VK_F);
		menuBar.add(menuFile);
		// Quit
		JMenuItem menuFileItemQuit = new JMenuItem("Quit");
		menuFileItemQuit.setMnemonic(KeyEvent.VK_Q);
		menuFileItemQuit
				.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.ALT_MASK));
		menuFileItemQuit.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent event) {
				System.exit(0);
			}
		});
		menuFile.add(menuFileItemQuit);

		// View menu
		JMenu menuView = new JMenu("View");
		menuView.setMnemonic(KeyEvent.VK_V);
		menuBar.add(menuView);
		// Restore all windows
		JMenuItem menuViewAllItems = new JMenuItem("Restore Views");
		menuViewAllItems.setMnemonic(KeyEvent.VK_0);
		menuViewAllItems
				.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_0, ActionEvent.ALT_MASK));
		menuViewAllItems.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent event) {
				dudesClientWindows.restoreWindows();
			}
		});
		menuView.add(menuViewAllItems);
		menuView.add(new JSeparator()); // SEPARATOR
		menuView.add(new JSeparator()); // SEPARATOR
		// Menu items (loop through all windows)
		// Hotkeys applied to the first 9 windows
		int[] hotkeys = { KeyEvent.VK_1, KeyEvent.VK_2, KeyEvent.VK_3, KeyEvent.VK_4,
				KeyEvent.VK_5, KeyEvent.VK_6, KeyEvent.VK_7, KeyEvent.VK_8, KeyEvent.VK_9 };
		for(int i = 0; dudesClientWindows.windows.length > i; i++) {
			final JInternalFrame curFrame = dudesClientWindows.windows[i];
			JMenuItem menuViewItem = new JMenuItem(curFrame.getTitle());
			if(i < 10) {
				menuViewItem.setMnemonic(hotkeys[i]);
				menuViewItem.setAccelerator(KeyStroke
						.getKeyStroke(hotkeys[i], ActionEvent.ALT_MASK));
			}
			menuViewItem.addActionListener(new ActionListener() {

				public void actionPerformed(ActionEvent event) {
					if(!curFrame.isVisible()) curFrame.setVisible(true);
					if(!curFrame.isIcon()) {
						try {
							curFrame.setIcon(false);
						} catch(Exception e) {}
					}
				}
			});
			menuView.add(menuViewItem);
		}

		return menuBar;
	}

	public static class dudesClientWindows {

		private static final int winW = content.getWidth();
		private static final int winH = content.getHeight() - 47;
		private static final int pad = 2;
		private static final int[] miniView = { winW - pad * 3 - 260, pad, // X,Y
				260 - pad, 200 }; // W,H
		private static final int[] chatView = { pad, winH - pad * 3 - 175, // X,Y
				350, 175 }; // W,H
		// World View window has dynamic dimensions
		// The dimensions are based on other windows, to fit all screen sizes
		private static final int[] worldView = { pad, pad, // X,Y
				(winW - pad * 4 - (miniView[2] + pad * 2)), // W
				(winH - pad * 3 - (chatView[3] + pad * 2)) }; // H

		private static final JInternalFrame[] windows = {
				dudesClientWindows.addInternalFrame("World View", worldView,
						getDudesIcon("world.png")),
				dudesClientWindows.addInternalFrame("Minimap", miniView, getDudesIcon("map.png")),
				dudesClientWindows.addInternalFrame("Chat", chatView, getDudesIcon("chat.png")) };
		private static final int[][] windowsDims = { worldView, miniView, chatView };

		private static JInternalFrame addInternalFrame(String title, int[] dimSettings, Image icon) {
			final JInternalFrame iFrame = new JInternalFrame(title, false, // resizable
					true, // closable
					false, // maximizable
					true); // iconifiable
			iFrame.setBounds(dimSettings[0], dimSettings[1], dimSettings[2], dimSettings[3]);
			iFrame.setFocusable(true);
			iFrame.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
			iFrame.setFrameIcon(new ImageIcon(icon));
			try {
				iFrame.setIcon(true);
			} catch(Exception e) {}
			iFrame.setVisible(true);
			System.out.println(iFrame.getTitle() + ":\t" + iFrame.getX() + ", " + iFrame.getY());
			return iFrame;
		}

		public class JBackgroundPanel extends JPanel {

			private static final long serialVersionUID = 1L;
			public void paintComponent(Graphics g) {
				Image img = getDudesImage(guiBackground);

				// Manual
				// int W = 100, H = 100;
				// Dynamic
				// int W = this.getWidth(), H = this.getHeight();
				// Fill entire desktop
				// int W = Toolkit.getDefaultToolkit().getScreenSize().width;
				// int H = Toolkit.getDefaultToolkit().getScreenSize().height;
				// 1:1
				int W = img.getWidth(this);
				int H = img.getHeight(this);

				// 0,0
				// int X = 0, Y = 0;
				// Center screen
				int X = Toolkit.getDefaultToolkit().getScreenSize().width / 2 - img.getWidth(this)
						/ 2;
				int Y = Toolkit.getDefaultToolkit().getScreenSize().height / 2
						- img.getHeight(this) / 2;

				g.drawImage(img, X, Y, W, H, this);
			}

		}
		private static void addWindows() {
			JInternalFrame background = new JInternalFrame("Background", false, // resizable
					false, // closable
					false, // maximizable
					false); // iconifiable);
			background.setBounds(-6, -25, Toolkit.getDefaultToolkit().getScreenSize().width + 12,
					Toolkit.getDefaultToolkit().getScreenSize().height - 14);
			background.setVisible(true);
			background.setFocusable(false);
			background.setEnabled(false);
			background.setIgnoreRepaint(true);
			try {
				background.setIcon(false);
			} catch(Exception e) {}
			try {
				background.setSelected(false);
			} catch(Exception e) {}

			JBackgroundPanel backgroundPanel = (new GUI_Backup_TI07.dudesClientWindows()).new JBackgroundPanel();
			backgroundPanel.setFocusable(false);
			backgroundPanel.setEnabled(false);
			backgroundPanel.setIgnoreRepaint(true);
			// Remove popup menu (right mouse click)
			backgroundPanel.addMouseListener(new MouseListener() {

				public void mouseClicked(MouseEvent arg0) {}
				public void mouseEntered(MouseEvent arg0) {}
				public void mouseExited(MouseEvent arg0) {}
				public void mousePressed(MouseEvent arg0) {}
				public void mouseReleased(MouseEvent arg0) {}
			});
			JPopupMenu popup = background.getComponentPopupMenu();
			if(popup != null) popup.setSize(0, 0);

			background.add(backgroundPanel, BorderLayout.CENTER);
			desktop.add(background, JLayeredPane.DEFAULT_LAYER);

			for(int i = 0; dudesClientWindows.windows.length > i; i++) {
				desktop.add(dudesClientWindows.windows[i], JLayeredPane.PALETTE_LAYER);
			}

		}

		private static void restoreWindows() {
			for(int i = 0; dudesClientWindows.windows.length > i; i++) {
				JInternalFrame curFrame = dudesClientWindows.windows[i];
				curFrame.setBounds(windowsDims[i][0], windowsDims[i][1], windowsDims[i][2],
						windowsDims[i][3]);
				if(!curFrame.isVisible()) curFrame.setVisible(true);
				if(curFrame.isIcon()) {
					try {
						curFrame.setIcon(false);
					} catch(Exception e) {
						e.printStackTrace();
					}
				}
			}
		}

		private static void fillWindows() {
			for(int i = 0; dudesClientWindows.windows.length > i; i++) {
				JInternalFrame curFrame = dudesClientWindows.windows[i];
				JPanel newPanel = new JPanel();
				if(i == 0) fillWindowWorldView(curFrame, newPanel);
				if(i == 1) fillWindowMiniMap(curFrame, newPanel);
				if(i == 2) fillWindowChatView(curFrame, newPanel);
				curFrame.add(newPanel);
			}
		}

		private static void fillWindowWorldView(JInternalFrame frame, JPanel panel) {

		}

		private static void fillWindowMiniMap(JInternalFrame frame, JPanel panel) {

		}

		/* public static String jsonToChat(String incomingJSON) { // JSONObject
		 * jsonObject = new JSONObject(); // jsonObject.put("test", "test"); //
		 * System.out.println(jsonObject);
		 * 
		 * incomingJSON =
		 * "{\"chats\":[[\"Laurens\",\"Dude\"],[\"Jesper\",\"Ja?\"],[\"Laurens\",\"Hoi!\"]]}"
		 * ;
		 * 
		 * JSONObject receivedJSON = (JSONObject)JSONValue.parse(incomingJSON);
		 * JSONArray chats = (JSONArray)receivedJSON.get("chats"); String
		 * chatTxt = ""; for(int i = 0; i < chats.size(); i++) { JSONArray chat
		 * = (JSONArray)chats.get(i);
		 * 
		 * String who = (String)chat.get(0); int width = 10; int addChars =
		 * width - who.length(); if (addChars < 0) return who.subSequence(0,
		 * width).toString(); final StringBuilder sb = new StringBuilder();
		 * sb.append(who); // Write the content ... while(--addChars > 0)
		 * sb.append("&nbsp;");
		 * 
		 * chatTxt += "<strong>" + sb.toString() + "</strong>" + chat.get(1) +
		 * "<br>\n"; } return chatTxt; } */

		private static final Font dudesFont = new Font("Lucida Console", Font.PLAIN, 12);
		private static final Color inputBgColorGlobal = new Color(215, 255, 189);
		private static final Color inputBgColorTeam = new Color(189, 210, 255);
		private static final Color dudesBorderColor = new Color(170, 170, 170);
		private static final JTextPane showChats = new JTextPane();
		private static final JComboBox chatAudience = new JComboBox();
		private static final JTextField chatTxtInput = new JTextField();
		private static final JButton chatBtnSubmit = new JButton();

		private static void fillWindowChatView(JInternalFrame frame, JPanel panel) {
			SpringLayout layout = new SpringLayout();
			panel.setLayout(layout);

			// Set layout (as shown below) - showChats
			// +---------------------------+
			// |...........................|
			// |... JTextPane showChats ...|
			// |...........................|
			// +---------------------------+
			// | JPanel inputPanel |
			// +---------------------------+

			showChats.setContentType("text/html");
			String addCSS = "body { font-family: " + dudesFont.getFamily() + ";" + " font-size:   "
					+ dudesFont.getSize() + "pt;" + " margin: 1px; padding: 1px; }";
			((HTMLDocument) showChats.getDocument()).getStyleSheet().addRule(addCSS);

			// showChats.setText(jsonToChat(""));

			JScrollPane showChatsScroll = new JScrollPane(showChats);
			showChatsScroll.setBorder(BorderFactory.createLineBorder(dudesBorderColor));
			showChatsScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
			panel.add(showChatsScroll);

			layout.putConstraint(SpringLayout.WEST, showChatsScroll, -1, SpringLayout.WEST, panel);
			layout.putConstraint(SpringLayout.NORTH, showChatsScroll, -1, SpringLayout.NORTH, panel);
			layout.putConstraint(SpringLayout.EAST, showChatsScroll, 1, SpringLayout.EAST, panel);
			layout.putConstraint(SpringLayout.SOUTH, showChatsScroll, -23, SpringLayout.SOUTH,
					panel);

			// Set layout (as shown below) - inputPanel
			// +---------------------------+
			// | |
			// | JTextPane ShowChats |
			// | |
			// +---------------------------+
			// |.... JPanel inputPanel ....|
			// +---------------------------+
			JPanel inputPanel = new JPanel();
			inputPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
			panel.add(inputPanel);
			layout.putConstraint(SpringLayout.WEST, inputPanel, -1, SpringLayout.WEST, panel);
			layout.putConstraint(SpringLayout.NORTH, inputPanel, -1, SpringLayout.SOUTH,
					showChatsScroll);
			layout.putConstraint(SpringLayout.EAST, inputPanel, 1, SpringLayout.EAST, panel);
			layout.putConstraint(SpringLayout.SOUTH, inputPanel, 1, SpringLayout.SOUTH, panel);

			inputPanel.setLayout(new BoxLayout(inputPanel, BoxLayout.X_AXIS));

			// JComboBox chatAudience
			inputPanel.add(chatAudience);
			String[] chatAudiences = { "Global", "Team" };
			for(int i = 0; i < chatAudiences.length; i++)
				chatAudience.addItem(chatAudiences[i]);
			chatAudience.setEditable(false);
			chatAudience.setSelectedIndex(0);
			chatAudience.setFont(dudesFont);
			chatAudience.addActionListener(new ActionListener() {

				public void actionPerformed(ActionEvent event) {
					if(chatAudience.getSelectedIndex() == 0)
						chatTxtInput
								.setBackground(inputBgColorGlobal); // Global
					else if(chatAudience.getSelectedIndex() == 1)
						chatTxtInput
								.setBackground(inputBgColorTeam); // Team
					else {}
				}
			});

			// JTextField chatTxtInput
			chatTxtInput.setFont(dudesFont);
			chatTxtInput.setBackground(inputBgColorGlobal);
			inputPanel.add(chatTxtInput);

			// JButton chatBtnSubmit
			chatBtnSubmit.setText("Send");
			chatBtnSubmit.setFont(dudesFont);
			inputPanel.add(chatBtnSubmit);
		}
	}
}
